package com.inspur.dgov.auth.controller;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.StrUtil;
import com.google.code.kaptcha.Producer;
import com.inspur.dgov.common.boot.operation.RedissonObject;
import com.inspur.dgov.common.tool.api.R;
import com.inspur.dgov.common.tool.constant.AppConstant;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 图形验证码控制器
 *
 * @Author chiyupei
 * @Date 19/9/30 下午2:12
 * @Version 1.0
 * @Description 图形验证码控制器
 */
@Slf4j
@RestController
@AllArgsConstructor
@RequestMapping("/kaptcha")
@Api(value = "图形验证码", tags = "图形验证码接口")
public class KaptchaController {

    private final Producer producer;

    private RedissonObject redissonObject;

    @GetMapping("/code")
    @ApiOperation(value = "生成验证码", notes = "传入随机数", position = 1)
    public R code(@ApiParam(value = "随机数") @RequestParam(value="random", required = true) String random) {
        if (StrUtil.isEmpty(random)) {
            return R.fail("接口调用不合法");
        }

        //生成验证码
        String text = producer.createText();
        BufferedImage image = producer.createImage(text);

        //保存验证码信息
        redissonObject.setValue(AppConstant.DEFAULT_CODE_KEY + random, text, Long.valueOf(120 * 1000));

        ByteArrayOutputStream out = null;
        try {
            //转换流输出
            out = new ByteArrayOutputStream();
            ImageIO.write(image, "jpeg", out);

            String base64Code = Base64.encode(out.toByteArray());
            String base64Img = "data:image/jpeg;base64," + base64Code.replace("\r\n", "");
            Map<String, Object> map = new HashMap<>();
            map.put("captcha", base64Img);
            return R.data(map);
        } catch (IOException e) {
            log.error("kaptcha err", e);
        } finally {
            try {
                if (null != out) {
                    out.close();
                }
            } catch (IOException e) {
                log.error("kaptcha err", e);
            }
        }
        return R.fail("验证码生成失败");
    }

    @PostMapping("/valid")
    @ApiOperation(value = "验证码校验", notes = "传入随机数和校验值", position = 2)
    public R valid(@ApiParam(value = "随机数") @RequestParam(value="random", required = true) String random,
                   @ApiParam(value = "校验值") @RequestParam(value="value", required = true) String value) {
        if (StrUtil.hasEmpty(random, value)) {
            return R.fail("接口调用不合法");
        }

        String key = AppConstant.DEFAULT_CODE_KEY + random;
        Object codeObj = redissonObject.getValue(key);
        if (null == codeObj) {
            return R.fail("验证码不合法");
        }

        String saveCode = codeObj.toString();
        if (StrUtil.isBlank(saveCode)) {
            redissonObject.delete(key);
            return R.fail("验证码不合法");
        }

        if (!StrUtil.equalsIgnoreCase(saveCode, value)) {
            redissonObject.delete(key);
            return R.fail("验证码不合法");
        }
        return R.success("");
    }
}
